package com.koron.common.core.business.common.service;

import com.koron.bean.system.org.OrgVo;
import com.koron.bean.system.role.AppOrgJurisdictionBean;
import com.koron.bean.system.role.UserOwnJurisdictionBean;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.StringUtils;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public interface CommonService {

    default String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }

    default EamUser getCurrUser() {
        return ThreadLocalContext.get();
    }

    //获取当前用户组织权限id(过滤出当前租户的组织)
    default List<String> getCurrUserOrgIds() {
        getCurrUser().getOrgVoList();
        UserOwnJurisdictionBean userOwnJurisdictionBean = getCurrUser().getUserOwnJurisdictionBean();
        if (Objects.isNull(userOwnJurisdictionBean)) {
            return new ArrayList<>();
        }

        List<AppOrgJurisdictionBean> appOrgJurisdictionBeanList = userOwnJurisdictionBean.getAppOrgJurisdictionBeanList();

        if (CollectionUtils.isEmpty(appOrgJurisdictionBeanList)) {
            return new ArrayList<>();
        }

        //当前水司为空情况下
        if (StringUtils.isEmpty(getCurrDs())) {
            List<String> list = new ArrayList<>();
            appOrgJurisdictionBeanList.forEach(p->list.addAll(p.getOrgStrList()));
            return list.stream().distinct().collect(Collectors.toList());
        }
        for (AppOrgJurisdictionBean appOrgJurisdictionBean : appOrgJurisdictionBeanList) {

            if (appOrgJurisdictionBean.getMark().equals(getCurrDs())) {
                return appOrgJurisdictionBean.getOrgStrList();
            }
        }

        return new ArrayList<>();
    }

    //获取当前用户组织权限id
    default  List<String> getCurrUserAllOrgIds() {
        UserOwnJurisdictionBean userOwnJurisdictionBean = getCurrUser().getUserOwnJurisdictionBean();
        if (Objects.isNull(userOwnJurisdictionBean)) {
            return new ArrayList<>();
        }

        List<AppOrgJurisdictionBean> appOrgJurisdictionBeanList = userOwnJurisdictionBean.getAppOrgJurisdictionBeanList();

        if (CollectionUtils.isEmpty(appOrgJurisdictionBeanList)) {
            return new ArrayList<>();
        }

        //当前水司为空情况下
        if (StringUtils.isEmpty(getCurrDs())) {
            List<String> list = new ArrayList<>();
            appOrgJurisdictionBeanList.forEach(p->list.addAll(p.getOrgStrList()));
            return list.stream().distinct().collect(Collectors.toList());
        }
        List<String> orgIdlist = new ArrayList<>();
        for (AppOrgJurisdictionBean appOrgJurisdictionBean : appOrgJurisdictionBeanList) {
            orgIdlist.addAll(appOrgJurisdictionBean.getOrgStrList());
        }
        return orgIdlist;
    }

}
